import dotenv
import logging
import functools


logger = logging.getLogger("render_service")


def log_config(_format: str, level: str):
    return {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {
                "()": "uvicorn.logging.DefaultFormatter",
                "fmt": _format,
                "datefmt": "%Y-%m-%d %H:%M:%S",

            },
        },
        "handlers": {
            "default": {
                "formatter": "default",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stderr",
            },
        },
        "loggers": {
            "render_service": {"handlers": ["default"], "level": level},
        },
    }


def check_float(key):
    return key in [
        "IOU_THRESHOLD",
        "CONFIDENCE_THRESHOLD"
    ]


@functools.cache
def config():
    _config = dotenv.dotenv_values(".env")
    for key, value in _config.items():
        if check_float(key):
            _config[key] = float(value)

    _config["log"] = log_config(
        _config.pop("LOG_FORMAT"),
        _config.pop("LOG_LEVEL")
    )
    return _config
